package org.hzero.order.app.service.impl;

import org.hzero.order.app.service.SoHeaderService;
import org.hzero.order.domain.entity.SoHeader;
import org.hzero.order.domain.entity.SoLine;
import org.hzero.order.domain.vo.SoHeaderVO;
import org.hzero.order.domain.vo.SoLineVO;
import org.hzero.order.domain.repository.SoHeaderRepository;
import org.hzero.order.domain.repository.SoLineRepository;
import org.hzero.order.infra.mapper.SoHeaderMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;


/**
 * @ Description   :  销售订单头应用服务默认实现
 * @ Author        :  xiong.yilin@hand-china.com
 * @ CreateDate    :  2019/8/8 10:30
 */
@Service //实现类，需要用 @Service 标注
public class SoHeaderServiceImpl implements SoHeaderService {

    @Autowired
    SoHeaderRepository soHeaderRepository;
    @Autowired
    SoLineRepository soLineRepository;
    @Autowired
    SoHeaderMapper soHeaderMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)//如果类加了这个注解，那么这个类里面的方法抛出异常，就会回滚，数据库里面的数据也会回滚
    public SoHeaderVO create(SoHeaderVO soHeaderVo) {
        int insert = soHeaderRepository.insert(soHeaderVo);
        List<SoLineVO> soLines = soHeaderVo.getSoLineList();
        if (insert > 0) {
            //增强for循环
            for (SoLine soLine : soLines) {
                soLine.setSoHeaderId(soHeaderVo.getSoHeaderId());
                soLineRepository.insert(soLine);
            }
        }
        return soHeaderVo;
    }

    @Override
    public List<SoHeaderVO> selectByConditions(SoHeader soHeader) {
        //根据条件查询订单头
        List<SoHeaderVO> soHeaders = soHeaderMapper.selectByConditions(soHeader);
        for (SoHeaderVO header : soHeaders) {
            Double sumMoney = 0.0;
            List<SoLineVO> soLineList = header.getSoLineList();
            for (SoLineVO soLineVo : soLineList) {
                sumMoney += soLineVo.getLineMoney();
            }
            header.setSumMoney(sumMoney);
        }
        return soHeaders;
    }

    @Override
    public SoHeaderVO updateById(SoHeader soHeader) {
        soHeaderMapper.updateById(soHeader);
        return null;
    }


}
